<template>
  <el-dialog v-model="dialogVisible" :title="parameter.title" width="680px" lock-scroll destroy-on-close draggable>
    <el-form ref="formRef" :model="parameter.rule" :rules="rules" label-width="100px" label-suffix=" :">
      <div class="custom-block tip">
        <p class="custom-block-title">规则参数值填写规则</p>
        <p>1. 规则类型 = “常量” 时，填写一个固定字符串</p>
        <p>2. 规则类型 = “计数” 时，填写计数起始值</p>
        <p>3. 规则类型 = “随机数” 时，填写最小值的随机数，最大随机数为同位数的“*9”</p>
      </div>
      <el-form-item label="排序" prop="ruleOrder">
        <el-input-number v-model="parameter.rule.ruleOrder" :min="1" :max="999999" :step="1" :precision="0" />
      </el-form-item>
      <el-form-item label="规则类型" prop="ruleType">
        <el-select v-model="parameter.rule.ruleType" clearable placeholder="请选规则类型">
          <el-option v-for="item in sequenceRuleTypeConst" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="parameter.rule.ruleType === 'const' || parameter.rule.ruleType === 'number' || parameter.rule.ruleType === 'random'"
        label="规则参数"
        prop="RuleValue"
      >
        <el-input v-model="parameter.rule.ruleValue" placeholder="请输入规则参数" clearable />
      </el-form-item>
      <el-form-item v-if="parameter.rule.ruleType === 'number'" label="补齐方向" prop="paddingSide">
        <el-select v-model="parameter.rule.paddingSide" clearable placeholder="请选补齐方向">
          <el-option v-for="item in sequencePaddingSideConst" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="parameter.rule.ruleType === 'number'" label="补齐宽度" prop="paddingWidth">
        <el-input v-model="parameter.rule.paddingWidth" placeholder="请输入补齐宽度" clearable />
      </el-form-item>
      <el-form-item v-if="parameter.rule.ruleType === 'number'" label="填充字符" prop="paddingChar">
        <el-input v-model="parameter.rule.paddingChar" placeholder="请输入填充字符" maxlength="1" clearable />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="parameter.rule.description" type="textarea" clearable />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">提交</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="sequenceRuleEdit">
import type { FormInstance, FormRules } from "element-plus";
import type { ResultData, SysSequenceRule } from "@/api/interface";
import { ref, reactive, watch } from "vue";
import { ElMessage } from "element-plus";
import { sequenceRuleTypeConst, sequencePaddingSideConst } from "@/utils/dict";

/** 系统序列 */
interface EditProps {
  /** 标题 */
  title: string;
  /** 待编辑的序列 */
  rule: Partial<SysSequenceRule.Form>;
  /** 获取表格数据的Api */
  getTableList?: () => void;
  /** 提交表单的Api */
  submitApi?: (params: any) => Promise<ResultData<boolean>>;
}

/** 表单实例 */
const formRef = ref<FormInstance>();
/** dialog 状态 */
const dialogVisible = ref(false);
/** 表单验证规则 */
const rules = reactive<FormRules>({
  ruleType: [
    { required: true, message: "请选择规则类型", trigger: "blur" },
    { min: 2, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur" }
  ]
});
/** 父组件传过来的参数 */
const parameter = ref<EditProps>({
  title: "",
  rule: {}
});

/**
 * 接收父组件参数
 *
 * @param params 父组件传过来的参数
 * @returns void
 */
const acceptParams = (params: EditProps) => {
  parameter.value = params;
  dialogVisible.value = true;
};

/**
 * 初始化表单
 *
 * 1. 重置表单
 *
 * @returns void
 */
const initFormInline = () => {
  formRef.value?.resetFields();
};

/**
 * 提交表单
 *
 * 1. 校验表单
 * 2. 提交表单
 * 3. 提交结果处理
 * 4. 异常处理
 *
 * @returns void
 */
const handleSubmit = () => {
  formRef.value
    // 1. 校验表单
    ?.validate()
    // 2. 提交表单
    .then(() => {
      return parameter.value.submitApi!(parameter.value.rule);
    })
    // 3. 提交结果处理
    .then(({ data }) => {
      if (data) {
        ElMessage.success({ message: `${parameter.value.title}成功！` });
        parameter.value.getTableList!();
        dialogVisible.value = false;
      } else {
        ElMessage.error({ message: `${parameter.value.title}失败！` });
      }
    })
    // 4. 异常处理
    .catch((error: Error) => {
      if (error.message) ElMessage.error({ message: `${parameter.value.title}异常：${error.message}` });
      else ElMessage.error({ message: "请检查表单数据是否填写完整！" });
    });
};

// 监听 dialogVisible 的变化
watch(dialogVisible, val => {
  if (val) {
    initFormInline();
  }
});

// 暴露给父组件的属性和方法
defineExpose({
  acceptParams
});
</script>

<style lang="scss" scoped>
.custom-block.tip {
  padding: 8px 16px;
  margin: 20px 0;
  background-color: #ecf5ff;
  border-left: 5px solid #409eff;
  border-radius: 4px;
}
.custom-block .custom-block-title {
  font-size: large;
  font-weight: 700;
}
p:first-child {
  margin-top: 0;
}
p {
  margin: 0.5rem 0;
  line-height: 1.7;
}
</style>
